package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.article.entity.ApArticle;
import com.heima.article.service.IApArticleService;
import com.heima.article.service.ITemplateService;
import com.heima.common.minio.MinIOService;
import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import freemarker.template.Configuration;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * @author zsk
 * @create 2022-04-15-21:14
 */
@Service
public class TemplateServiceImpl implements ITemplateService {

    @Autowired
    private Configuration configuration;

    @Autowired
    private MinIOService minIOService;

    @Autowired
    private IApArticleService apArticleService;

    /**
     * 保存文章自动生成静态页面
     * @param article
     * @param content
     */
    @Override
    public void createHtml(ApArticle article, String content) {

        try {
            System.out.println(Thread.currentThread().getName() + "生成静态html服务开始运行");
            //根据配置找到对应的模板
            Template template = configuration.getTemplate("article.ftl");

            //封装数据
            Map<String,Object> map = new HashMap<>();
            map.put("content", JSON.parseArray(content));

            //合并模板和数据
            StringWriter out = new StringWriter();
            template.process(map,out);

            //上传静态页面到minio中
            InputStream is = new ByteArrayInputStream(out.toString().getBytes());

            String url = minIOService.upload(article.getId() + ".html", is, "text/html");

            //将url更新到文章详情中
            article.setStaticUrl(url);
            apArticleService.updateById(article);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
